package com.example.demo.util.minio;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.demo.util.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin //处理跨域请求
@RequestMapping("/minioFile")
public class MinioFileController {

    @Resource
    private MinioClientUtils minioClientUtils;

    @Resource
    private MinioConfig minioConfig;

    @PostMapping(value = "/uploadFile")
    public String uploadFile(@RequestParam("files") List<MultipartFile> files) {
        log.info(files.toString());
        if (CollectionUtils.isEmpty(files)){
            return "未选择文件！";
        }

        List<String> MinioResponseDTOList = new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
//            获取文件拓展名
            String extName = FileUtil.extName(originalFilename);
            log.info("文件拓展名:"+extName);
//            生成新的文件名，存入到minio
            long millSeconds = Instant.now().toEpochMilli();
            String minioFileName=millSeconds+ RandomStringUtils.randomNumeric(12)+"."+extName;
            String contentType = file.getContentType();
            log.info("文件mime:{}",contentType);
//            返回文件大小,单位字节
            long size = file.getSize();
            log.info("文件大小："+size);
            try {
                String bucketName = minioConfig.getBucketName();
                minioClientUtils.putObject(bucketName,file,minioFileName);
                String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);
                MinioResponseDTOList.add(fileUrl);
            } catch (Exception e) {
                log.error("上传文件出错:{}",e);
                return e.getMessage();
            }
        }
        return String.join(",",MinioResponseDTOList);
    }

    /**
     * 删除文件
     * @param minioFileName 文件名称
     * @return
     */
    @RequestMapping(value = "/deleteMinioFile",method = RequestMethod.GET)
    public Result<?> deleteMinioFile(@RequestParam String minioFileName){
        try {
            String bucketName = minioConfig.getBucketName();
            minioClientUtils.removeObject(bucketName,minioFileName);
        }catch (Exception e){
            log.error("删除文件失败！");
            return Result.error(e);
        }
        return Result.ok("删除文件成功");
    }
}
